import pygame
import os
import time

pygame.mixer.init(frequency=44100, size=-16, channels=2, buffer=1024)

SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))

music_loaded = False
music_playing = False
loaded_music_path = ""

try:
    files_in_dir = os.listdir(SCRIPT_DIR)
    print(f"Files in directory: {files_in_dir}")
    
    mp3_files = [f for f in files_in_dir if f.lower().endswith('.mp3')]
    print(f"Found MP3 files: {mp3_files}")
    
    if mp3_files:
        music_file = os.path.join(SCRIPT_DIR, mp3_files[0])
        print(f"Attempting to load: {music_file}")
        pygame.mixer.music.load(music_file)
        music_loaded = True
        loaded_music_path = music_file
        print(f"Successfully loaded music file: {music_file}")

        pygame.mixer.music.set_volume(0.8)
        print("Volume set to 80%")
    else:
        print(f"Warning: No MP3 files found in directory: {SCRIPT_DIR}")
except Exception as e:
    print(f"Error initializing music: {e}")
    import traceback
    traceback.print_exc()

def play_background_music():
    """Play background music in loop if available"""
    global music_loaded, music_playing
    try:
        current_status = pygame.mixer.music.get_busy()
        print(f"Music status - Loaded: {music_loaded}, Currently playing: {current_status}, Tracked as playing: {music_playing}")
        
        if music_loaded:
            if current_status:
                pygame.mixer.music.stop()
                print("Stopped currently playing music")
                time.sleep(0.1)
            
            pygame.mixer.music.play(-1)
            music_playing = True
            print("Background music started (loop mode)")

            time.sleep(0.5)
            if pygame.mixer.music.get_busy():
                print("✓ Music is now playing")
            else:
                print("✗ Music failed to start playing")
        else:
            print("Cannot play music: No music file loaded")

            reload_music()
    except Exception as e:
        print(f"Error playing music: {e}")
        import traceback
        traceback.print_exc()

def reload_music():
    """Attempt to reload music file"""
    global music_loaded, loaded_music_path
    try:
        print("Attempting to reload music...")
        files_in_dir = os.listdir(SCRIPT_DIR)
        mp3_files = [f for f in files_in_dir if f.lower().endswith('.mp3')]
        
        if mp3_files:
            music_file = os.path.join(SCRIPT_DIR, mp3_files[0])
            pygame.mixer.music.load(music_file)
            music_loaded = True
            loaded_music_path = music_file
            pygame.mixer.music.set_volume(0.8)
            print(f"Successfully reloaded music: {music_file}")
            return True
        return False
    except Exception as e:
        print(f"Failed to reload music: {e}")
        return False

def pause_music():
    """Pause the currently playing music"""
    global music_playing
    try:
        current_status = pygame.mixer.music.get_busy()
        print(f"Pausing music - Currently playing: {current_status}")
        pygame.mixer.music.pause()
        music_playing = False
        print("✓ Music paused")
    except Exception as e:
        print(f"Error pausing music: {e}")
        import traceback
        traceback.print_exc()

def unpause_music():
    """Resume playing paused music"""
    global music_playing
    try:
        print("Resuming paused music")
        pygame.mixer.music.unpause()
        music_playing = True
        # Verify it's playing
        time.sleep(0.2)
        if pygame.mixer.music.get_busy():
            print("✓ Music resumed successfully")
        else:
            print("✗ Music failed to resume")
    except Exception as e:
        print(f"Error resuming music: {e}")
        import traceback
        traceback.print_exc()

def stop_music():
    """Stop the currently playing music"""
    global music_playing
    try:
        current_status = pygame.mixer.music.get_busy()
        print(f"Stopping music - Currently playing: {current_status}")
        pygame.mixer.music.stop()
        music_playing = False
        print("✓ Music stopped")
    except Exception as e:
        print(f"Error stopping music: {e}")
        import traceback
        traceback.print_exc()

def get_music_status():
    """Get current music playback status"""
    return {
        "loaded": music_loaded,
        "playing": pygame.mixer.music.get_busy(),
        "tracked_playing": music_playing,
        "volume": pygame.mixer.music.get_volume(),
        "file": loaded_music_path
    }

def set_volume(volume_level):
    """Set music volume
    
    Args:
        volume_level: Float between 0.0 and 1.0
    """
    try:
        volume_level = max(0.0, min(1.0, volume_level))
        pygame.mixer.music.set_volume(volume_level)
        print(f"Volume set to {volume_level * 100:.0f}%")
    except Exception as e:
        print(f"Error setting volume: {e}")